import 'dart:async';
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/views/base/MaterialListParmEditVC.dart';
import 'package:yuellyfactory/views/dto/PriceMaterial.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';
import 'ParmVC.dart';

class MaterialListParmVC extends StatefulWidget {

  final PricePart pricePart;
  final VoidCallback callback;
  const MaterialListParmVC({super.key, required this.pricePart, required this.callback});

  @override
  State<MaterialListParmVC> createState() => _MaterialListParmVCState();
}

class _MaterialListParmVCState extends State<MaterialListParmVC> {

  StreamSubscription? streamSubscription;
  List parmList=[];
  final dialogKey = GlobalKey<ShadFormState>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    streamSubscription = eventBus.on<EventRefreshPart>().listen((event) {
      getDetail();
    });
    getDetail();
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      constraints: const BoxConstraints(minWidth: 1000,maxWidth: 1000),
      title: const Text('零件参数编辑'),

      onClosing: (){
        widget.callback();
      },
      child: Column(
        children: [
          Row(
            children: [
              Text('参数',style: TextStyle(color:Colors.black,fontSize: ViewUtil.fontSize(22)),),
              Expanded(child: Container()),
              ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=widget.pricePart.id;
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  MaterialListParmEditVC(
                    pricePart: widget.pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              }),
              if(parmList.isEmpty)
              IconButton(icon: const Icon(Icons.copy_all),color:ColorUtil.colorBlue,
                iconSize: ViewUtil.screenWidth(35),onPressed: (){
                  getAllMaterial();
                },)


            ],
          ),
          ConstrainedBox(constraints: const BoxConstraints(maxHeight: 500 ),
            child:
            DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                horizontalMargin: 12,
                columns: [
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入数据'),
                    fixedWidth: 400,
                  ),

                ],
                rows: getDataRows()

            ),


          )
        ],
      ),
    );
  }




  getDataRows(){
    List<DataRow> datas=[];
    for (var item in parmList) {
      datas.add(DataRow(cells: [
        DataCell(
          Row(
            children: [
              ViewUtil.editIcon('编辑参数',(){showShadSheet(
                side: ShadSheetSide.right,
                barrierColor: Colors.transparent,
                context: context,
                builder: (context) =>  MaterialListParmEditVC(
                  pricePart: widget.pricePart,
                  priceParm: item,
                  callback: () {
                    //回调
                    getDetail();
                  },),
              );}),
              ViewUtil.delIcon('删除参数',(){
                delParm(item);
              })
            ],
          )

        ),
        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.handle==0?'输入数据':'录入公式')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.handle==0?item.value:getRuleString(item.rule))),
      ]));


    }
    return datas;
  }


  void delParm(PriceParm priceParm){

    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${priceParm.name}吗?'),
        description: const Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将取消配置',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              requestDelParm(priceParm);
            },
          ),
        ],
      ),
    );

  }

  void requestDelParm(PriceParm priceParm){
    var parm={
      "id":priceParm.id
    };
    BaseRequest.postHttp('price/materialparmdel',parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        ToastUtil.showToast("删除成功");
        getDetail();
        Navigator.pop(context);
      }
    }, onError: (error){});
  }



  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);

      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }

  void getDetail(){
    var parm={"id":widget.pricePart.id};

    BaseRequest.postHttp("price/materialdetail",parameters:parm , canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        PricePart pricePart= PricePart.fromJson(datas);
        widget.pricePart.parmList=pricePart.parmList;
        parmList=pricePart.parmList;
        widget.pricePart.rule=pricePart.rule;
        setState(() {

        });
      }
    }, onError: (error){

    });
  }


  void getAllMaterial(){
    var parm={
      "id":widget.pricePart.serialId
    };
    BaseRequest.postHttp('price/baseallserialmaterial',parameters: parm, canTip: true , context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];
        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          if(id!=widget.pricePart.id){
            items[id]=name;
          }

        }
        addMatterialDialog(items);
      }
    }, onError: (error){

    });
  }


  void addMatterialDialog(var options) {
    //选择零件列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitCopyParm();
            },)
            ],
            child:
            ShadForm(
                key: dialogKey,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ShadSelectFormField<String>(
                      id: 'material',
                      label: const Text('材料'),
                      minWidth: 350,
                      options: (options as Map).entries
                          .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                          .toList(), // 注意添加toList()转换
                      selectedOptionBuilder: (context, value) {
                        if (value == null || value == 'none') {
                          return const Text('请选择要拷贝的材料');
                        }
                        // 使用空值合并运算符??代替!，提供默认值
                        return Text((options as Map)[value]?.toString() ?? '未知选项');
                      },
                      placeholder: const Text('请选择要拷贝的材料'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择要拷贝的材料';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 10),

                  ],
                )

            )

        )
    );

  }

  void submitCopyParm(){

    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var material = values["material"];



    var parm={
      "partId":widget.pricePart.id,
      "copyId":material,
    };
    //copymaterialparm
    BaseRequest.postHttp('price/copymaterialparm',parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        ToastUtil.showToast("操作成功");
        getDetail();
        Navigator.pop(context);
      }
    }, onError: (error){});
  }
  }
}